package org.gas.barapraja.handler;

import org.apache.log4j.Logger;
import org.gas.barapraja.db.dao.MessageDao;
import org.gas.barapraja.db.entity.Message;
import org.gas.barapraja.handler.validator.RequestValidator;
import org.gas.barapraja.proc.PduProcessor;
import org.gas.barapraja.proc.buffer.AppQueuePool;
import org.gas.barapraja.proc.buffer.MsgQueue;
import org.gas.barapraja.util.GasAppContext;

import com.logica.smpp.pdu.SubmitMultiSM;
import com.logica.smpp.pdu.SubmitMultiSMResp;
import com.logica.smpp.pdu.WrongLengthOfStringException;

public class MultiMsgHandler extends RequestHandlerAdapter {
	
	private static final Logger logger=Logger.getLogger(MultiMsgHandler.class);
	
	private TokenDetails tokenDetails;
	
	private MessageComposer composer;
	
	
	public MultiMsgHandler(PduProcessor processor) {
		super();
		setPduProcessor(processor);
		composer=new MessageComposer();
		tokenDetails=new AccountTokenDetails();
	}


	@Override
	public int handleRequest(SubmitMultiSM multiSM) {
		int status=validator.validate(multiSM);
		try{
			if(status==RequestValidator.TOKEN_OK){
				logger.info("token status OK. composing submit multi messages");
				int size=multiSM.getNumberOfDests();
				Message[] messages=composer.compose(multiSM, size);
				MessageDao messageDao=GasAppContext.springConfiguredBean(MessageDao.class);
				MsgQueue msgQueue=AppQueuePool.msgQueueInstance();
				for(int i=0;i<=messages.length;i++){
					messageDao.persist(messages[i]);
					msgQueue.queue(messages[i]);
				}
				tokenDetails.decreaseToken(size);
				SubmitMultiSMResp multiSMResp=(SubmitMultiSMResp)multiSM.getResponse();
				multiSMResp.setMessageId(String.valueOf(size));
				pduProcessor.serverResponse(multiSMResp);
			}else{
				
			}
		}catch(WrongLengthOfStringException e){
			
		}
		return status;
	}
	
	
	

}
